<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>打卡统计报表</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: '微软雅黑';
            background: rgb(255, 255, 255);
        }
        .main-content {
            width: 100%;
            padding: 24px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .action-bar {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
        }
        input, select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 160px;
            font-size: 13px;
        }
        button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }
        .btn-search {
            background: #1890ff;
            color: white;
        }
        .btn-export {
            background: #52c41a;
            color: white;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border: 1px solid #e8e8e8;
            margin-top: 12px;
        }
        th, td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #e8e8e8;
            font-size: 13px;
        }
        th {
            background: #fafafa;
            color: rgba(0,0,0,0.85);
        }
        .pagination {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-top: 16px;
            color: #999;
            font-size: 13px;
        }
        .btn-prev, .btn-next {
            padding: 6px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s;
        }
        .btn-prev:hover, .btn-next:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        .btn-prev:disabled, .btn-next:disabled {
            color: #d9d9d9;
            border-color: #d9d9d9;
            cursor: not-allowed;
        }
        #pageInfo {
            min-width: 60px;
            text-align: center;
        }
        .chart-container {
            margin-top: 24px;
            height: 400px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 16px;
        }
    </style>
</head>
<body>
<div class="main-content">
    <h3 style="margin-bottom:16px;color:rgba(0,0,0,0.85)">打卡统计报表</h3>

    <div class="action-bar">
        <input type="datetime-local" id="startDate" placeholder="开始日期">
        <input type="datetime-local" id="endDate" placeholder="结束日期">

        <button class="btn-search" onclick="searchRecords()">查询</button>
        <button class="btn-export" onclick="exportReport()">导出报表</button>
<script>
function exportReport() {
    if ($('#reportTable tbody tr').length === 0) {
        alert('没有数据可导出');
        return;
    }
    const wb = XLSX.utils.table_to_book(document.getElementById('reportTable'));
    const filename = '打卡报表_' + new Date().toISOString().slice(0, 10) + '.xlsx';
    XLSX.writeFile(wb, filename);
}
</script>
    </div>

    <div class="chart-container" id="chartDiv">
        <!-- 这里将放置统计图表 -->
        <p style="text-align:center;color:#999;line-height:400px;">暂无统计数据，请先查询</p>
    </div>

    <table id="reportTable">
        <thead>
        <tr>
            <th>学生编号</th>
            <th>姓名</th>
            <th>房间号</th>
            <th>手机号</th>
            <th>打卡时间</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过JavaScript动态加载 -->
        </tbody>
    </table>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script>
    // 动态加载ECharts
    function loadScript(url, callback) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
        script.onload = callback;
        document.head.appendChild(script);
    }

    // 修改全局变量
    let chartInstance = null;
    let isEChartsReady = false;
    let retryCount = 0; // 添加重试计数器

    // 修改初始化逻辑
    $(document).ready(function() {
        loadScript('https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js', function() {
            if(typeof echarts === 'undefined') {
                console.error('ECharts加载失败');
                return;
            }
            
            try {
                chartInstance = echarts.init(document.getElementById('chartDiv'));
                // 初始化空图表
                chartInstance.setOption({
                    title: {
                        text: '打卡统计',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [{
                        name: '打卡情况',
                        type: 'pie',
                        radius: '50%',
                        data: []
                    }]
                });
                isEChartsReady = true;
                
                // 设置默认日期
                const today = new Date();
                const firstDay = new Date(today.getFullYear(), today.getMonth(), 1, 0, 0);
                const endDay = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59);
                $("#startDate").val(formatDate(firstDay));
                $("#endDate").val(formatDate(endDay));
            } catch (e) {
                console.error('图表初始化失败:', e);
            }
        });
    });

    // 日期格式化
    // 修改日期格式化函数
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    function formatDateForBackend(dateStr) {
        if (!dateStr) {
            console.error("日期为空");
            return null;
        }
        // 处理浏览器生成的 ISO 格式（YYYY-MM-DDTHH:mm）
        // 将 T 替换为空格，得到 YYYY-MM-DD HH:mm
        const formattedStr = dateStr.replace('T', ' ');
        // 直接返回带秒的格式（后端可能需要精确到秒，默认补 00 秒）
        return `${formattedStr}:00`;
    }
    
    // 初始化图表
    function initChart() {
        const chart = echarts.init(document.getElementById('chartDiv'));
        chart.setOption({
            title: {
                text: '打卡统计',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '打卡情况',
                    type: 'pie',
                    radius: '50%',
                    data: [],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        });
    }

    // 查询打卡记录
    function formatDateForBackend(dateStr) {
        if (!dateStr) {
            console.error("日期为空");
            return null;
        }
        
        try {
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) {
                console.error("无效的日期:", dateStr);
                return null;
            }
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:00`;
        } catch (e) {
            console.error("日期格式化错误:", e);
            return null;
        }
    }
    
    function searchRecords() {
        const startDateVal = $("#startDate").val();
        const endDateVal = $("#endDate").val();
        
        if(!startDateVal || !endDateVal) {
            alert("请选择开始和结束日期");
            return;
        }

        // 直接替换 T 为空格，并补秒
        const startDate = startDateVal.replace('T', ' ') + ":00";
        const endDate = endDateVal.replace('T', ' ') + ":00";


        // 验证格式（可选）
        if (!/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:00$/.test(startDate) ||
            !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:00$/.test(endDate)) {
            alert("日期格式无效，请重新选择");
            return;
        }

        console.log("发送的查询参数:", { startDate, endDate });
        
        $.ajax({
            url:"<%=request.getContextPath()%>/ClockReportController",
            type: "POST",
            dataType:"json",
            data:{
              op:"search",
              startDate: startDate,
              endDate: endDate
            },
            success:function (data){
                console.log("返回数据详情:", JSON.stringify(data, null, 2));
                if(Array.isArray(data)) {
                    updateTable(data);
                    updateChart(data);
                } else {
                    console.error("返回数据格式错误:", data);
                    alert("获取数据失败，请检查控制台");
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX请求错误:", status, error);
                alert("请求失败: " + error);
            }
        });
    }

    function updateTable(data) {
        let html = '';
        if (!Array.isArray(data)) {
            console.error('返回数据不是数组:', data);
            $("#reportTable tbody").html('<tr><td colspan="6" class="text-center">无数据或数据格式错误</td></tr>');
            return;
        }

        $.each(data, function (index, record) {
            // 添加防御性检查
            if (!record) {
                console.warn('第' + index + '条记录为空');
                return true; // 跳过当前记录
            }
            
            // 检查clockTime是否存在，不存在则使用默认值
            const clockTime = record.clockTime || '';
            console.log('处理记录:', index, record);
            
            let formattedTime = formatDisplayTime(clockTime);
            let tr = '<tr>' +
                '<td>' + (record.studentId || '') + '</td>' +
                '<td>' + (record.studentName || '') + '</td>' +
                '<td>' + (record.roomNumber || '') + '</td>' +
                '<td>' + (record.phone || '') + '</td>' +
                '<td>' + formattedTime + '</td>' +
                '<td>' + (record.status == '1' ? '正常' : '异常') + '</td>' +
                '</tr>';
            html += tr;
        });
        $("#reportTable tbody").html(html);
    }

    function formatDisplayTime(timeStr) {
        if (!timeStr) return '';
        let date;
        try {
            if (typeof timeStr === 'number') {
                date = new Date(timeStr);
            } else if (typeof timeStr ==='string') {
                // 尝试按ISO 8601格式解析
                if (timeStr.includes('T')) {
                    timeStr = timeStr.replace('T','');
                }
                date = new Date(timeStr);
            }
        } catch (e) {
            console.error('时间转换错误:', e);
            return timeStr;
        }
        // 检查日期是否有效
        if (date &&!isNaN(date.getTime())) {
            return new Intl.DateTimeFormat('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            }).format(date);
        }
        return timeStr;
    }



    // 更新图表
    function updateChart(data) {
        if (!isEChartsReady || !chartInstance) {
            if (retryCount < 5) { // 最多重试5次
                retryCount++;
                console.log('ECharts未准备好，第' + retryCount + '次重试...');
                setTimeout(() => updateChart(data), 200);
            } else {
                console.error('ECharts初始化失败，无法显示图表');
            }
            return;
        }
        
        try {
            // 统计打卡状态
            let normalCount = 0;
            let abnormalCount = 0;
        
            data.forEach(record => {
                if (record.status == '1') {
                    normalCount++;
                } else {
                    abnormalCount++;
                }
            });
        
            // 更新图表选项
            chartInstance.setOption({
                series: [{
                    data: [
                        {
                            value: normalCount,
                            name: '正常打卡',
                            itemStyle: { color: '#52c41a' }
                        },
                        {
                            value: abnormalCount,
                            name: '异常打卡',
                            itemStyle: { color: '#ff4d4f' }
                        }
                    ]
                }]
            });
            retryCount = 0; // 重置重试计数器
        } catch (e) {
            console.error('更新图表失败:', e);
        }
    }
</script>
</body>
</html>